import { useEffect, useCallback } from 'react'

import { useDispatch } from 'react-redux'


/**
 * 调用该函数,返回一个函数,改变搜索下拉框的状态(默认为false)
 * 改变搜索下拉框的状态
 */
export function useChangeDropBoxState(state = false) {
    const dispatch = useDispatch()
    let timer = null;
    return () => {
        timer && clearTimeout(timer)
        timer = setTimeout(() => {
            console.log('first执行了');
            // dispatch(changeFocusStateAction(state))
            console.log('清楚；');
        }, 400)
    }
}

/**
 * 调用该hook注册全局键盘事件: ctrl+k唤醒搜索框  esc关闭下拉框
 */

export const useGlobalKeyboardEvn = () => {
        const showBox = useChangeDropBoxState(true);
        const closeBox = useChangeDropBoxState(false);
        const handleKeyDown = useCallback((e) => {
            console.log(e.key);
            if (e.ctrlKey && e.key === 'k') {
                e.preventDefault();
                showBox()
                return
            }
            if (e.key === 'Escape') {
                closeBox()
            }

        }, [showBox, closeBox])

        useEffect(() => {
            console.log('new');
            document.addEventListener('keydown', handleKeyDown)
            return () => {
                document.removeEventListener('keydown', handleKeyDown)
                console.log('ole');
            }

        }, [handleKeyDown])
    }
    /**
     * 唤醒登录框
     */
    // export async function useAwakenModal() {
    //   const dispatch = useDispatch()
    //   dispatch(changeIsVisible(true))
    // }